/**
 * Copyright(c) 2010 Ceno Techonologies Co., Ltd.
 *
 * History:
 *   15-12-16 上午11:17 Created by piaohh
 */
package com.jade.bss.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.jade.bss.base.customer.Customer;
import com.jade.bss.base.customer.CustomerAddress;
import com.jade.bss.base.customer.CustomerAddressManager;
import com.jade.bss.base.customer.CustomerManager;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.CriterionUtils;
import com.jade.framework.base.criterion.MatchMode;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.base.util.PagingResult;
import com.jade.framework.base.util.ResponseUtils;
import com.jade.modules.region.RegionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 用户地址管理
 * @author <a href="mailto:Administrator@ceno.cn">piaohh</a>
 * @version 1.0 15-12-16 上午11:17
 */
@RestController
@RequestMapping (value = "/address", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(value = "用户地址", description = "用户管理地址")
public class CustomerAddressController
{
    private CustomerAddressManager customerAddressManager = ApplicationContextUtils.getBean("bss_customerAddressManager");
    private CustomerManager customerManager = ApplicationContextUtils.getBean("bss_customerManager");
   // @RequiresAuthentication
    @RequiresPermissions (value = {"address:view"})
    @RequestMapping (value = "/query", method = RequestMethod.GET)
    @ApiOperation(value = "查询用户地址", httpMethod = "GET", response = CustomerAddress.class)
    public void query(@ApiParam(value = "关键词") @RequestParam (value = "keyword", required = false) String keyword,
                      @ApiParam(value = "用户id") @RequestParam (value = "customerId", defaultValue = "0") long customerId,
                      @ApiParam(value = "地址类型") @RequestParam (value = "type", required = false) String type,
                      @ApiParam(value = "起始值") @RequestParam (value = "offset", defaultValue = "0") int offset,
                      @ApiParam(value = "每页大小") @RequestParam (value = "length", defaultValue = "10") int length,
                      @ApiParam(value = "排序字段") @RequestParam (value = "sort", required = false) String sortName,
                      @ApiParam(value = "排序规则", allowableValues = "desc, asc") @RequestParam (value = "order", required = false,defaultValue = "asc") String sortType,
                      HttpServletResponse response) throws Exception
    {
        Criteria criteria = new Criteria(offset, length);
        if (StringUtils.isNotBlank(keyword)) {
            CriterionUtils.addQuery(criteria, new String[]{"name","company","address","zipcode","mobile","email"}, keyword, MatchMode.ANYWHERE, null);
        }
        if (StringUtils.isNotBlank(type)) {
            criteria.add(Restrictions.eq("type",type));
        }
        if(customerId>0)
            criteria.add(Restrictions.eq("customerId",customerId));
        CriterionUtils.addOrder(criteria, sortName, sortType, "id");
        PagingList<CustomerAddress> addresses = customerAddressManager.queryAddress(criteria);
        PagingResult result = PagingResult.getResult(addresses);
        Map<Long,Customer> customerMap = new HashMap<Long, Customer>();
        Map<Long,String> regionMap = new HashMap<Long, String>();
        for(CustomerAddress address : addresses)
        {
            if(customerMap.get(address.getCustomerId())==null)
            {
                Customer customer = customerManager.getCustomer(address.getCustomerId());
                if(customer!=null)
                    customerMap.put(customer.getId(),customer);
            }
            if(regionMap.get(address.getId())==null)
            {
                String area = getAreaName(address);
                if(StringUtils.isNotBlank(area))
                    regionMap.put(address.getId(),area);
            }
        }
        result.setParam("regionMap",regionMap);
        result.setParam("customerMap",customerMap);
        ResponseUtils.writeSuccessPagingResult(response, result);
    }

    protected String getAreaName(CustomerAddress address)
    {
        String area = "";
        String province = RegionUtils.getName(address.getProvince());
        if(StringUtils.isNotBlank(province))
            area+=province+"-";
        String city = RegionUtils.getName(address.getCity());
        if(StringUtils.isNotBlank(city))
            area+=city+"-";
        String county = RegionUtils.getName(address.getCounty());
        if(StringUtils.isNotBlank(county))
            area+=county+"-";
        if(StringUtils.isNotBlank(area))
            area = area.substring(0,area.length()-1);
        return area;
    }

    @ResponseBody
    @RequiresAuthentication
    @RequestMapping (value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取指定用户地址", httpMethod = "GET")
    public void get(@ApiParam(value = "地址id") @PathVariable long id,HttpServletResponse response)
            throws Exception
    {
        CustomerAddress address = customerAddressManager.getAddress(id);
        ResponseUtils.writeSuccessResult(response, address);
    }

    @ResponseBody
    @RequiresAuthentication
    @RequiresPermissions (value = {"address:add"})
    @RequestMapping (value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "增加用户地址", httpMethod = "POST")
    public void add(@ApiParam(value = "地址对象") @RequestBody CustomerAddress address, HttpServletResponse response)
            throws Exception
    {
        customerAddressManager.addAddress(address);
        ResponseUtils.writeSuccessResult(response);
    }

    @ResponseBody
    @RequiresAuthentication
    @RequestMapping (value = "/getDefault", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户默认地址", httpMethod = "GET")
    public void getDefault(@ApiParam(value = "用户id") @RequestParam (value = "customerId") long customerId ,
                           HttpServletResponse response)
            throws Exception
    {
        Criteria criteria = new Criteria(-1,-1);
        criteria.add(Restrictions.eq("customerId",customerId));
        criteria.add(Restrictions.eq("isDefault",true));
        List<CustomerAddress> list = customerAddressManager.queryAddress(criteria);
        CustomerAddress customerAddress = null;
        if(list!=null&&list.size()>0)
            customerAddress = list.get(0);
        ResponseUtils.writeSuccessResult(response,customerAddress);
    }

    @ResponseBody
    @RequiresAuthentication
    @RequiresPermissions (value = {"address:remove"})
    @RequestMapping (value = "/remove", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除用户地址", httpMethod = "DELETE")
    public void remove(@ApiParam(value = "地址id") @RequestParam ("id") long[] ids, HttpServletResponse response)
            throws Exception
    {
        customerAddressManager.removeAddress(ids);
        ResponseUtils.writeSuccessResult(response);
    }

    @ResponseBody
    @RequiresAuthentication
    @RequiresPermissions (value = {"address:edit"})
    @RequestMapping (value = "/edit", method = RequestMethod.PUT)
    @ApiOperation(value = "修改用户地址", httpMethod = "PUT")
    public void edit(@ApiParam(value = "地址对象") @RequestBody CustomerAddress address, HttpServletResponse response)
            throws Exception
    {
        customerAddressManager.updateAddress(address);
        ResponseUtils.writeSuccessResult(response);
    }

    @ResponseBody
    @RequiresAuthentication
    @RequestMapping (value = "/list", method = RequestMethod.GET)
    @ApiOperation(value = "查询用户地址列表", httpMethod = "GET")
    public void list(@ApiParam(value = "用户id") @RequestParam (value = "customerId", defaultValue = "0") long customerId,
                     @ApiParam(value = "地址类型") @RequestParam (value = "type", required = false) String type,
                     HttpServletResponse response)
            throws Exception
    {
        List<CustomerAddress> addresses = customerAddressManager.listAddress(customerId,type);
        ResponseUtils.writeSuccessResult(response,addresses);
    }

    @ResponseBody
    @RequiresAuthentication
    @RequestMapping (value = "/setDefault", method = RequestMethod.POST)
    @ApiOperation(value = "设置用户默认地址", httpMethod = "POST")
    public void setDefaultAddress(@ApiParam(value = "用户id") @RequestParam (value = "customerId") long customerId,
                                  @ApiParam(value = "地址类型") @RequestParam (value = "type") String type,
                                  @ApiParam(value = "地址id") @RequestParam (value = "id") long id,
                                  HttpServletResponse response) throws Exception
    {
        customerAddressManager.setDefaultAddress(customerId,type,id);
        ResponseUtils.writeSuccessResult(response);
    }
}
